03. Invoking Object Methods
Functions vs. Methods
At this point, we've mostly seen objects with properties that behave more like attributes. That is, properties such as color or type are data that describe an object, but they don't "do" anything. We can extend functionality to objects by adding methods to them.
Say that we have a function, sayHello(), which simply logs a message to the console:
function sayHello () {
console.log('Hi there!');
}
Now, say that we also have a developer object with a single property, name:
const developer = {
name: 'Andrew'
};
If we want to add the sayHello() function into the developer object, we can add the same way as we add other new properties: by providing property name, then giving it a value. This time, the value of the property is a function!
developer.sayHello = function () {
console.log('Hi there!');
};
This is how the updated developer object looks:
{
name: 'Andrew',
sayHello: function () {
console.log('Hi there!');
}
}
So now that a sayHello property has been defined, how do we go about calling (i.e., invoking) its referenced function?
Calling Methods
We can access a function in an object using the property name. Again, another name for a function property of an object is a method. We can access it the same way that we do with other properties: by using dot notation or square bracket notation. Let's take a look back at the updated developer object above, then invoke its sayHello() method:
const developer = {
name: 'Andrew',
sayHello: function () {
console.log('Hi there!');
}
};
developer.sayHello();
// 'Hi there!'
developer['sayHello']();
// 'Hi there!'
Just like calling a function, an object's method is called by adding parentheses at the end of the method's name. Note that both dot notation and square bracket notation return the same result!
Passing Arguments Into Methods
If the method takes arguments, you can proceed the same way, too:
const developer = {
name: 'Andrew',
sayHello: function () {
console.log('Hi there!');
},
favoriteLanguage: function (language) {
console.log(`My favorite programming language is ${language}`);
}
};
developer.favoriteLanguage('JavaScript');
// My favorite programming language is JavaScript'
Let's see this all in action!
L1 -38 - Calling Methods Demo V1
SOLUTION:
- A method is a property that points to a function.
QUESTION:
Write an expression that invokes the alerter() function in the following array, myArray:
const myArray = [ function alerter() { alert('Hello!'); } ];
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
QUESTION:
Write an expression that invokes the function referenced by the bell object's ring property:
const bell = {
color: 'gold',
ring: function () {
console.log('Ring ring ring!');
}
};
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
π‘ Call Methods by Property Name π‘
We've been using anonymous functions (i.e., functions without a name) for object methods. However, naming those functions is still valid JavaScript syntax. Consider the following object,
greeter:
const greeter = { greet: function sayHello() { console.log('Hello!'); } };
Note that the
greetproperty points to a function with a name:sayHello. Whether this function is named or not,greetis invoked the same way:
greeter.greet(); // 'Hello!'
Named functions are great for a smoother debugging experience, since those functions will have a useful name to display in stack traces. They're completely optional, however, and you'll often read code written by developers who prefer one way or the other.
A Method Can Access the Object it was Called On
Recall that an object can contain data and the means to manipulate that data. But just how can an object reference its own properties, much less manipulate some of those properties itself? This is all possible with the this keyword!
Using this, methods can directly access the object that it is called on. Consider the following object, triangle:
const triangle = {
type: 'scalene',
identify: function () {
console.log(`This is a ${this.type} triangle.`);
}
};
Note that inside the identify() method, the value this is used. When you say this, what you're really saying is "this object" or "the object at hand." this is what gives the identify() method direct access to the triangle object's properties:
triangle.identify();
// 'This is a scalene triangle.'
When the identify() method is called, the value of this is set to the object it was called on: triangle. As a result, the identify() method can access and use triangle's type property, as seen in the above console.log() expression.
Note that this is a reserved word in JavaScript, and cannot be used as an identifier (e.g. variable names, function names, etc.).
L1-45 - This Demo V1
SOLUTION:
- Using `this`, methods can access and manipulate an object's properties.
- `this` is a reserved word in JavaScript.
QUESTION:
Let's make sure we're still on the same page! Write an expression that invokes the function referenced by the tree object's growOneFoot property:
const tree = {
type: 'redwood',
leaves: 'green',
height: 80,
age: 15,
growOneFoot: function () {
this.height += 1;
}
};
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
Start Quiz:
/*
Create an object called `chameleon` with two properties:
1. `color`, whose value is initially set to 'green' or 'pink'
2. `changeColor`, a function which changes `chameleon`'s `color` to 'pink'
if it is 'green', or to 'green' if it is 'pink'
*/
π‘ The value of
thisπ‘
Depending on how a function is called,
thiscan be set to different values! Later in this course, we'll take a deep dive into different ways that functions can be invoked, and how each approach influences the value ofthis.
Summary
A method is a function property of an object. It is accessed the same way as any other property of the object (i.e., using dot notation or square bracket notation), and is invoked the same way as a regular function outside of an object (i.e., adding parentheses to the end of the expression).
Since an object is a collection of data and the means to operate on that data, a method can access the object it was called on using the special this keyword. The value of this is determined when a method is invoked, and its value is the object on which the method was called. Since this is a reserved word in JavaScript, its value cannot be used as an identifier. Feel free to check out the links below for an additional look at methods and their relationship with this.
We've spent a bit of time on this inside objects, but did you know that the value of this can have different meanings outside an object? In the next section, we'll take a close look at globals, their relationship with this, and the implications of using them.